package com.kinptm.masterclock.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

import com.j256.ormlite.dao.RuntimeExceptionDao;
import com.kinptm.masterclock.Intents;
import com.kinptm.masterclock.bean.AlarmClock;
import com.kinptm.masterclock.bean.TimerRecord;
import com.kinptm.masterclock.db.DbHelper;
import com.kinptm.masterclock.utils.AlarmUtil;
import com.kinptm.masterclock.utils.Ln;

import org.joda.time.DateTime;

/**
 * Created by pc on 13-11-11.
 */
public class AlarmReceiver extends BroadcastReceiver {

    public void onReceive(Context context, Intent intent) {
        if (Intents.ALARM.ACTION_CLOCK_RECEIVER.equals(intent.getAction())) {
            AlarmClock alarmClock = DbHelper.getInstance().getAlarmClockDao().
                    queryForId(intent.getExtras().getInt(Intents.ALARM.EXTRA_ALARM_ID));

            Ln.d("%s 时间到, 闹铃响啦~!", new DateTime(alarmClock.getAlarmMillis()).toString("yyyy-MM-dd HH:mm:ss"));


            if (!alarmClock.getRepeat().isEmpty()) {
                Ln.d("重复闹钟 : %s ", alarmClock.getRepeat());
                AlarmUtil.nextAlarmClock(alarmClock);
                AlarmUtil.plan2AlarmClock(alarmClock);
                alarmClock.setEnable(true);
            } else {
                alarmClock.setEnable(false);
                Ln.d("无重复闹钟!");
            }

            DbHelper.getInstance().getAlarmClockDao().update(alarmClock);
            Ln.e(alarmClock);

            Intents.launchAlarmRang(context, alarmClock);
        } else if (Intents.ALARM.ACTION_TIMER_RECEIVER.equals(intent.getAction())) {
            int id = intent.getExtras().getInt(Intents.ALARM.EXTRA_ALARM_ID);
            RuntimeExceptionDao<TimerRecord, Integer> dao = DbHelper.getInstance().getTimerRecordDao();
            TimerRecord record = dao.queryForId(id);
            record.setFinish(true);
            dao.update(record);
            Ln.d("计时器到, 闹铃响啦~!", record.getTime().toString("yyyy-MM-dd HH:mm:ss"));
            Ln.e(record);
            Intents.launchAlarmRang(context, record);
        }
    }
}
